package com.jiang.jixiang.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginBehavior;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.android.gms.auth.api.identity.GetSignInIntentRequest;
import com.google.android.gms.auth.api.identity.Identity;
import com.google.android.gms.auth.api.identity.SignInCredential;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.AccountBean;
import com.jiang.jixiang.bean.UserInfoBean;
import com.jiang.jixiang.databinding.ActivityLoginBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.countdown.CountDown;
import com.ws.universal.tools.countdown.TimeCount;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.KeystoreUtils;
import com.ws.universal.tools.utils.LocationUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;
import com.ws.universal.tools.utils.cache.CacheDoubleStaticUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoginActivity extends BaseActivity implements NetWorkListener {
    /**
     * Google 访问令牌 要用web端的客户端ID
     */
    private final String ServerClientId = "625037881388-40k9v692jg04o7kvgm2akmq3u443djll.apps.googleusercontent.com";
    private ActivityLoginBinding binding;
    private Intent intent;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    /*手机/邮箱登录参数*/
    private String accountParams;
    private String passwordParams;
    private String codeParams;
    private String areaParams;
    private UserInfoBean userInfoBean;
    private Bundle bundle;
    private boolean isRememberPwd = false; //是否记住密码

    private final ActivityResultLauncher googleLoginLauncher = registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(), result -> {
        try {
            SignInCredential signInClient = Identity.getSignInClient(this).getSignInCredentialFromIntent(result.getData());
            LogcatUtils.e(" getId " + signInClient.getId());
            loginOther(signInClient.getId(), "google");
        } catch (ApiException e) {
            e.printStackTrace();
            LogcatUtils.e("TAG  signInResult:failed code=" + e.getStatusCode());
        }
    });

    private TimeCount timeCount;
    private List<AccountBean> accountBeanList;
    private CallbackManager metaCallbackManager;
    private int agreement;

    @Override
    protected void initCreate(Bundle savedInstanceState) {
        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ManageActivity.removeActivity("PermissionActivity");

    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        binding.inTitle.titleTextTv.setVisibility(View.GONE);
        binding.inTitle.titleRightBtn.setVisibility(View.VISIBLE);
        binding.inTitle.titleRightBtn.setText(getString(R.string.language));
        accountBeanList = GsonUtils.parseJArray(CacheDoubleStaticUtils.getString(Constants.rememberPwd), AccountBean.class);
        if (accountBeanList == null) {
            accountBeanList = new ArrayList<>();
        }


        binding.inTitle.titleLeftBtn.setOnClickListener(view -> {
            onBackPressed();
        });

        binding.inTitle.titleRightBtn.setOnClickListener(view -> {
            Intent intent = new Intent(getContext(), LanguageActivity.class);
            intent.putExtra("type", 1);
            startActivity(intent);
        });
        binding.tvForgotPassword.setOnClickListener(v -> {
            areaParams = binding.tvArea.getText().toString().trim();
            intent = new Intent(this, RetrievePwdActivity.class);
            intent.putExtra("isRegist", false);
            intent.putExtra("areaParams", areaParams);
            startActivity(intent);
        });
        binding.tvRegister.setOnClickListener(view -> {
            intent = new Intent(this, RegisterActivity.class);
            intent.putExtra("isRegist", false);
            intent.putExtra("areaParams", binding.tvArea.getText().toString().toString());
            startActivity(intent);
        });

        StringUtils.generateSp(binding.tvProtocol, getString(R.string.agreed_protocol), true, getColor(R.color.main_color), getColor(R.color.main_color), new StringUtils.PublicTextCallback() {
            @Override
            public void onProtocolOnClick(int index) {
                loadAgreement(index);
            }

        }, getString(R.string.service_agreement), getString(R.string.privacy_policy));


        binding.rlLoginGoogle.setOnClickListener(view -> {
            loginGoogle();
        });

        initFaceBook();
        binding.rlLoginFaceBook.setOnClickListener(view -> {
            //LoginManager.getInstance().setLoginBehavior(LoginBehavior.NATIVE_WITH_FALLBACK);
            //LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
            AccessToken accessToken = AccessToken.getCurrentAccessToken();
            boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
            LogcatUtils.e(" isLoggedIn " + isLoggedIn);
            if (!isLoggedIn) {
                LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_ONLY);
                LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
            } else {

                loginOther(accessToken.getUserId(), "facebook");
            }

        });


      /*  binding.btnGetCode.setOnClickListener(v -> {
            hideSoftInput(binding.tvGetCode);
            accountParams = binding.edAccount.getText().toString().trim();
            areaParams = binding.tvArea.getText().toString().trim();
            if (TextUtils.isEmpty(accountParams)) {
                ToastUtils.showShort(getString(R.string.phone_cannot_be_empty));
                return;
            }
            getCode();
        });*/


        binding.btnSignIn.setChangeAlphaWhenPress(true);
        binding.btnSignIn.setOnClickListener(view -> {
            if (check(false)) {

                hideSoftInput(binding.btnSignIn);

                loginAccount();
            }


        });

        binding.llCountry.setOnClickListener(view -> {

            Intent intent = new Intent(this, CountryActivity.class);
            intentActivityResultLauncher.launch(intent);

        });

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
                    String tel = result.getData().getStringExtra(CountryActivity.resultCountyCode);
                    LogcatUtils.e("获取的 Tel " + tel);
                    binding.tvArea.setText(tel);
                }
            }

        });


        binding.llAgreePass.setOnClickListener(v -> {

            if (!isRememberPwd) {
                isRememberPwd = true;
                binding.imgAgreePass.setImageResource(R.mipmap.icon_oval_choose_remenbered);
                binding.tvKeep.setTextColor(getColor(R.color.main_color));
            } else {
                isRememberPwd = false;
                binding.imgAgreePass.setImageResource(R.mipmap.icon_oval_choose_remenber);
                binding.tvKeep.setTextColor(getColor(R.color.main_color2));

            }
            LogcatUtils.e(" isRememberPwd  " + isRememberPwd);
        });


     /*   binding.tvLoginHint.setOnClickListener(view -> {
            KeystoreUtils.checkKeyStoreHash(getActivity());
        });*/

        timeCount = new TimeCount();
        timeCount.setCountDown(new CountDown() {
            @Override
            public void onTick(long millisUntilFinished) {
                binding.btnGetCode.setEnabled(false);
                //binding.tvGetCode.setText(StringUtils.getString("重新发送", "(", millisUntilFinished / 1000 + ")"));
                binding.btnGetCode.setText(StringUtils.getString(millisUntilFinished / 1000));
            }

            @Override
            public void onTickFinish() {
                binding.tvGetCode.setText(R.string.get_code);
                binding.btnGetCode.setEnabled(true);
                binding.btnGetCode.setTextColor(ContextCompat.getColor(getContext(), R.color.text_minor_color));
            }
        });

        binding.edPwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    accountParams = binding.edAccount.getText().toString().trim();
                    // EditText获取焦点时执行的操作
                    if (isHaveAccount(accountParams) != -1) {
                        binding.edPwd.setText(accountBeanList.get(isHaveAccount(accountParams)).passwordParams);
                        binding.tvArea.setText(accountBeanList.get(isHaveAccount(accountParams)).areaParams);
                        binding.edPwd.clearFocus();
                        hideSoftInput(binding.edPwd);
                    }
                } else {
                    // EditText失去焦点时执行的操作
                }
            }
        });
        //getArea();


    }

    //记住密码
    private void rememberPwd() {
        if (isHaveAccount(accountParams) == -1) {
            accountBeanList.add(new AccountBean(areaParams, accountParams, passwordParams));
        }
        CacheDoubleStaticUtils.put(Constants.rememberPwd, GsonUtils.toJsonArrayWithSerializeNulls(accountBeanList));
        LogcatUtils.e(" rememberPwd  " + CacheDoubleStaticUtils.getString(Constants.rememberPwd));
    }

    private int isHaveAccount(String accountParams) {
        for (int i = 0; i < accountBeanList.size(); i++) {
            if (accountParams.equals(accountBeanList.get(i).accountParams)) {
                return i;
            }
        }
        return -1;
    }

/*    private void getCode() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        params.put("area", areaParams);
        params.put("phone", accountParams);
        params.put("type", "login");
        okHttpModel.post(ApiUrl.smsCode_Api, params, ApiUrl.smsCode_Api_ID, this);
    }*/

    private void initFaceBook() {
        LogcatUtils.e(" initFaceBook ");
        metaCallbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(metaCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult result) {
                LogcatUtils.e("TAG initFaceBook ", "Meta login success");
                LogcatUtils.e("TAG initFaceBook ", "Meta login account info userId:" + result.getAccessToken().getUserId());
                LogcatUtils.e("TAG initFaceBook ", "Meta login account info token:" + result.getAccessToken().getToken());
                LogcatUtils.e("TAG initFaceBook ", "Meta login account info applicationId:" + result.getAccessToken().getApplicationId());

                loginOther(result.getAccessToken().getUserId(), "facebook");
            }

            @Override
            public void onCancel() {
                LogcatUtils.e("TAG initFaceBook ", "Meta login canceled");
            }

            @Override
            public void onError(@NonNull FacebookException error) {
                LogcatUtils.e("TAG initFaceBook ", "Meta login failed error:" + error.getMessage());
            }
        });

    }

    private void loginGoogle() {
        LogcatUtils.e(" loginGoogle ");
        //使用GoogleSignIn.getLastSignedInAccount方法为当前登录的用户请求个人资料信息。
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        //不存在则请求登录
        if (account == null) {
            GetSignInIntentRequest sign = GetSignInIntentRequest.builder().setServerClientId(ServerClientId).build();
            Identity.getSignInClient(this).getSignInIntent(sign).addOnSuccessListener(new OnSuccessListener<PendingIntent>() {
                @Override
                public void onSuccess(PendingIntent pendingIntent) {
                    googleLoginLauncher.launch(new IntentSenderRequest.Builder(pendingIntent).build());
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    LogcatUtils.e(" 登录失败 " + e.getMessage());
                    LogcatUtils.e(" 登录失败 " + e);
                }
            });
        } else {
            loginOther(account.getId(), "google");
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        //binding.edCodeAndPwd.setInputType(TEXT_PASSWORD);
    }

    private void loginAccount() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        params.put("phone", accountParams);
        params.put("area", areaParams);
        params.put("password", passwordParams);
        params.put("type", "mobile");
        params.put("push_id", Constants.push_id);
        okHttpModel.post(ApiUrl.login_Api, params, ApiUrl.login_Api_ID, this);
    }


    //第三方登录
    private void loginOther(String openid, String type) {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        params.put("openid", openid);
        params.put("push_id", Constants.push_id);
        params.put("type", type);
        okHttpModel.post(ApiUrl.login_Api, params, ApiUrl.login_Api_ID, this);
    }

    //获取默认区号
    private void getArea() {

        Map<String, String> params = new HashMap<>();
        String countryCode = "";
        if (getLocation() != null) {
            countryCode = LocationUtils.getInstance().getLocationCountryCode(getContext(), getLocation().getLatitude(), getLocation().getLongitude());
        }
        params.put("code", countryCode);
        okHttpModel.post(ApiUrl.getArea_Api, params, ApiUrl.getArea_Api_ID, this);

    }

    private boolean check(boolean isGetCode) {
        accountParams = binding.edAccount.getText().toString().trim();
        areaParams = binding.tvArea.getText().toString().trim();
        passwordParams = binding.edCode.getText().toString().trim();
        if (TextUtils.isEmpty(accountParams)) {
            ToastUtils.showShort(getString(R.string.phone_cannot_be_empty));
            return false;
        }

        if (TextUtils.isEmpty(passwordParams)) {
            ToastUtils.showShort(getString(R.string.password_cannot_be_empty));
            return false;
        }


        return true;
    }

    //获取协议
    private void loadAgreement(int agreement) {
        this.agreement = agreement;
        Map<String, String> params = new HashMap<>();
        if (agreement == 0) {
            params.put("type", "server");
        } else {
            params.put("type", "privacy");
        }
        okHttpModel.post(ApiUrl.agreement_Api, params, ApiUrl.agreement_Api_ID, this);
    }


    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.smsCode_Api_ID:

                stopProgressDialog();
                int time = data.optInt("time");
                timeCount.setmMillisInFuture(time * 1000);
                timeCount.start();
                ToastUtils.showLong(commonality.getMessage(), 3000);

                break;
            case ApiUrl.login_Api_ID:
                if (isRememberPwd) {
                    rememberPwd();
                }
                CacheUtils.setString(Constants.token, data.optString("token"));
                CacheUtils.setString(Constants.client, "android");
                CacheUtils.setBoolean(Constants.isLogin, true);

                userInfoBean = GsonUtils.parseJObject(data.toString(), UserInfoBean.class);
                if (userInfoBean != null) {
                    PubDiaUtils.getInstance().saveUserInfo(data.toString());
                }

                ToastUtils.showShort(commonality.getMessage());
               /* if (userInfoBean.getFirst_login() == 1) {
                    pageJump(RegistInviteActivity.class);
                } else {
                    pageJump(MainActivity.class);
                }*/
                pageJump(MainActivity.class);
                BaseBusData baseBusData = new BaseBusData(BusCode.LogIn);
                EventBusUtil.postEvent(baseBusData);
                finish();
                ToastUtils.showShort(commonality.getMessage());
                break;

            case ApiUrl.agreement_Api_ID:
                bundle = new Bundle();
                if (agreement == 0) {
                    bundle.putString("title", getString(R.string.service_agreement));
                } else if (agreement == 1) {
                    bundle.putString("title", getResources().getString(R.string.privacy_policy));
                }
                bundle.putString("loadH5Url", data.optString("url"));
                pageJump(AllHtmlActivity.class, bundle);

                break;
            case ApiUrl.getArea_Api_ID:
                binding.tvArea.setText(data.optString("area"));
                areaParams = data.optString("area");
                CacheUtils.setString(Constants.areaParams, areaParams);
                break;


        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }

    @Override
    protected void FinishDesTroy() {
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        metaCallbackManager.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

}
